<?php

class TasksApp extends ECBaseApp
{

    function index()
    {
        exit;
    }

    /**
     *    自动确认指定时间后未确认收货的订单
     *
     *    @author    yanhj 2014.08.14
     */
    function auto_confirm()
    {
        $now = gmtime();
        $interval = 10 * 24 * 3600; //默认15天
        $model_order = & m('order');
        $model_returns =& m("returns");

        /* 确认收货 */
        /* 款到发货的订单 */
        $orders = $model_order->find(array(
            'fields' => 'order_id',
            'conditions' => "ship_time + {$interval} < {$now} AND status = " . ORDER_SHIPPED,
        ));
        /* 货到付款的订单 */
        $cod_orders = $model_order->find(array(
            'fields' => 'order_id',
            'conditions' => "ship_time + {$interval} < {$now} AND status =" . ORDER_SHIPPED . ' AND payment_code=\'cod\'',
        ));

        if (empty($orders) && empty($cod_orders))
        {
            $this->log('auto_confirm'); //记录日志
            return;
        }

        /* 操作日志 */
        $order_logs = array();
        $order_shipped = order_status(ORDER_SHIPPED);
        $order_finished = order_status(ORDER_FINISHED);

        /* 款到发货的订单 */
        if (!empty($orders))
        {
            /* 更新订单状态 */
            $model_order->edit(array_keys($orders), array('status' => ORDER_FINISHED, 'finished_time' => gmtime()));

            /* 更新商品统计 */
            $model_goodsstatistics = & m('goodsstatistics');
            $model_ordergoods = & m('ordergoods');
            $order_goods = $model_ordergoods->find('order_id ' . db_create_in(array_keys($orders)));

            $tmp1 = $tmp2 = array();
            foreach ($order_goods as $goods)
            {
                if(isset($tmp1[$goods['goods_id']]))
                    $tmp1[$goods['goods_id']] += $goods['quantity'];
                else
                    $tmp1[$goods['goods_id']] = $goods['quantity'];
            }
            foreach ($tmp1 as $_goods_id => $_quantity)
            {
                $tmp2[$_quantity][] = $_goods_id;
            }
            foreach ($tmp2 as $_quantity => $_goods_ids)
            {
                $model_goodsstatistics->edit($_goods_ids, "sales=sales+{$_quantity}");
            }

            /* 操作记录 */
            foreach ($orders as $order_id => $order)
            {
                $order_logs[] = array(
                    'order_id' => $order_id,
                    'operator' => '0',
                    'order_status' => $order_shipped,
                    'changed_status' => $order_finished,
                    'remark' => '',
                    'log_time' => $now,
                );
                //关闭退货退款申请
                $model_returns->close_returns($order_id, 1);
            }
        }

        /* 货到付款的订单 */
        if (!empty($cod_orders))
        {
            /* 修改订单状态 */
            $model_order->edit(array_keys($cod_orders), array(
                'status' => ORDER_FINISHED,
                'pay_time' => $now,
                'finished_time' => $now
            ));

            /* 操作记录 */
            foreach ($cod_orders as $order_id => $order)
            {
                $order_logs[] = array(
                    'order_id' => $order_id,
                    'operator' => '0',
                    'order_status' => $order_shipped,
                    'changed_status' => $order_finished,
                    'remark' => '',
                    'log_time' => $now,
                );
            }
        }

        $order_log = & m('orderlog');
        $order_log->add($order_logs);
        $this->log('auto_confirm'); //记录日志
    }

    /**
     *    自动好评确认收货的订单
     *
     *    @author    yanhj 2014.08.14
     */
    function auto_evaluate()
    {
        $now = gmtime();

        /* 默认7天未评价自动好评 */
        $interval = 7 * 24 * 3600;

        /* 获取满足条件的订单 */
        $model_order = & m('order');

        /* 指定时间后已确认收货的未评价的 */
        $orders = $model_order->find(array(
            'conditions' => "finished_time + {$interval} < {$now} AND evaluation_status = 0 AND status = " . ORDER_FINISHED,
            'fields' => 'order_id, seller_id, buyer_id, buyer_name, finished_time',
        ));

        if ($orders)
        {
            $order_ids = array_keys($orders);

            /* 获取待评价的商品列表 */
            $model_ordergoods = & m('ordergoods');
            $order_goods = $model_ordergoods->find(array(
                'conditions' => 'order_id ' . db_create_in($order_ids),
                'fields' => 'rec_id, goods_id, quantity, order_id',
            ));


            foreach ($orders as $order_id => $order)
            {
                $store_comment[] = array(
                    'comment_type' => 1,
                    'order_id' => $order['order_id'],
                    'from_user_name' => $order['buyer_name'],
                    'evaluation' => 3,
                    'comment' => '',
                    'add_time' => $this->_get_auto_evaluate_time($order['finished_time']),
                    'to_user_id' => $order['seller_id'],
                    'from_user_id' => $order['buyer_id'],
                    'credit_value' => 0
                );
            }

            $comments = array();
            foreach ($order_goods as $rec_id => $og)
            {
                $comments[$og['goods_id']] ++;
                $evaluations[] = array(
                    'comment_type' => 0,
                    'order_id' => $og['order_id'],
                    'goods_id' => $og['goods_id'],
                    'from_user_name' => $orders[$og['order_id']]['buyer_name'],
                    'evaluation' => 5,
                    'comment' => $this->_get_auto_evaluate_comment(),
                    'add_time' => $this->_get_auto_evaluate_time($orders[$og['order_id']]['finished_time']),
                    'to_user_id' => $orders[$og['order_id']]['seller_id'],
                    'from_user_id' => $orders[$og['order_id']]['buyer_id'],
                    'credit_value' => 0,
                    'quantity' => $og['quantity'],
                    'is_edit' => 1,
                );
            }

            $model_comment = & m('comment');
            $model_comment->add($store_comment); //写入买家对商铺评价
            $model_comment->add($evaluations); //写入商品评价
            //更新订单的评价状态
            $model_order->edit($order_ids, array(
                'evaluation_status' => 1,
                'evaluation_time' => gmtime()
            ));

            $edit_comments = array();
            foreach ($comments as $og_id => $t)
            {
                $edit_comments[$t][] = $og_id;
            }

            $model_goodsstatistics = & m('goodsstatistics');
            foreach ($edit_comments as $times => $goods_ids)
            {
                $model_goodsstatistics->edit($goods_ids, 'comments=comments+' . $times);
            }
        }

        $this->log('auto_evaluate'); //记录日志
    }

    /**
     *    自动关闭过期的店铺
     *
     *    @author    yanhj 2014.08.14
     */
    function close_expired_store()
    {
        $store_mod = & m('store');
        $stores = $store_mod->find(array(
            'conditions' => "state = '" . STORE_OPEN . "' AND end_time > 0 AND end_time < '" . gmtime() . "'",
            'join' => 'belongs_to_user',
            'fields' => 'store_id, user_id, user_name, email',
        ));

        if ($stores)
        {
            $ms = & ms();
            $store_ids = $store_emails = array();

            /* 消息内容 */
            $content = get_msg('toseller_store_expired_closed_notify');

            foreach ($stores as $store)
            {
                $store_ids[] = $store['store_id'];
                $store_emails[] = $store['email'];
            }

            $ms->pm->send(MSG_SYSTEM, $store_ids, '', $content);
            $store_mod->edit($store_ids, array('state' => STORE_CLOSED, 'close_reason' => Lang::get('toseller_store_expired_closed_notify')));
        }


        $this->log('close_expired_store'); //记录日志
    }

    /**
     *    退货退款超时操作
     *
     *    @author    yanhj 2014.08.14
     */
    function auto_returns()
    {
        $now = gmtime();
        $interval = 5 * 24 * 3600; //默认5天
        $confirm_interval = 10 * 24 * 3600; //自动确认
        $returns_mod = & m('returns');
        $returns_log_mod = m('returnslog');

        /* 买家申请退货退款,卖家没有响应时的操作 */
        $returns_agree = $returns_mod->find(array(
            'fields'    => 'returns_id,type,status,seller_id',
            'conditions'=> "add_time + {$interval} < {$now} AND status = 1",
        ));

        if ($returns_agree)
        {
            $address_mod =& m('selleraddress');            
            $edit_data1 = array(
                'status' => 7,
                'confirm_time' => $now,
                'report_reason' => '卖家逾期未处理，默认同意'
            );

            $edit_data2 = array(
			'status'      => 3,
			'agree_time'  => $now,
            'agree_msg'   => '卖家超时未响应，本次申请自动达成。',
			);
            foreach($returns_agree as $key => $returns)
            {
                /* 退款 */
                if ($returns['type'] == 1)
                {
                    $returns_ids1[] = $returns['returns_id'];
                }
                /*退货退款*/
                if($returns['type'] == 2)
                {                   
                    $returns_ids2[] = $returns['returns_id'];
                    $addr_id = $address_mod->getOne("SELECT addr_id FROM  {$address_mod->table} WHERE type=1 AND user_id = {$returns['seller_id']} ORDER BY is_deafult DESC,addr_id DESC");                  
                    $edit_data2['addr_id'] = intval($addr_id);                 
                }             
                $log_data[] = array(
                    'returns_id' => $returns['returns_id'],
                    'operator' => '系统',
                    'remark' => '卖家超时未响应。本次申请自动达成。',
                    'log_time' => $now,
                );
            }

            /* 修改退货退款状态 */
            if ($returns_ids1)
            {
                $returns_mod->edit('returns_id ' . db_create_in($returns_ids1), $edit_data1);
            }
            if ($returns_ids2)
            {
                $returns_mod->edit('returns_id ' . db_create_in($returns_ids2), $edit_data2);
            }

            /* 添加到退货退款日志表 */
            $returns_log_mod->add($log_data);
        }

        /* 卖家拒绝退货退款,买家没有响应时的操作 */
        $returns_refuse = $returns_mod->find(array(
            'fields' => 'returns_id,type',
            'conditions' => "refuse_time + {$interval} < {$now} AND status = 4 ",
        ));

        if ($returns_refuse)
        {
            $edit_data = array(
                'status' => -1,
                'close_type' => 4,
                'finished_time' => $now,
            );
            foreach ($returns_refuse as $key => $returns)
            {
                $returns_ids[] = $returns['returns_id'];

                $log_data[] = array(
                    'returns_id' => $returns['returns_id'],
                    'operator' => '系统',
                    'remark' => '买家超时未响应。本次申请自动关闭。',
                    'log_time' => $now,
                );
                $returns_mod->send_returns_email($returns['buyer_id'], $returns['returns_id'], 8); //发送邮件给买家;               
            }

            /* 修改退货退款状态 */
            $returns_mod->edit('returns_id ' . db_create_in($returns_ids), $edit_data);

            /* 添加到退货退款日志表 */
            $returns_log_mod->add($log_data);
        }

        /* 卖家同意退货退款,买家没有发货响应时的操作 */
        $returns_shipping = $returns_mod->find(array(
            'fields' => 'returns_id,type',
            'conditions' => "agree_time + {$interval} < {$now} AND status = 3 AND type = 2",
        ));

        if ($returns_shipping)
        {
            $edit_data = array(
                'status' => -1,
                'close_type' => 4,
                'finished_time' => $now,
            );

            foreach ($returns_shipping as $key => $returns)
            {
                $returns_ids[] = $returns['returns_id'];

                $log_data[] = array(
                    'returns_id' => $returns['returns_id'],
                    'operator' => '系统',
                    'remark' => '买家超时未响应。本次申请自动关闭。',
                    'log_time' => $now,
                );

                $returns_mod->send_returns_email($returns['buyer_id'], $returns['returns_id'], 8); //发送邮件给买家;               
            }

            /* 修改退货退款状态 */
            $returns_mod->edit("returns_id " . db_create_in($returns_ids), $edit_data);

            /* 添加到退货退款日志表 */
            $returns_log_mod->add($log_data);
        }

        /* 买家已经发货,卖家没有确认响应时的操作 */
        $returns_shipping = $returns_mod->find(array(
            'fields' => 'returns_id,type',
            'conditions' => "shipping_time + {$confirm_interval} < {$now} AND status = 5 AND type = 2",
        ));
        if ($returns_shipping)
        {
            $edit_data = array(
                'status' => 7,
                'confirm_time' => $now,
                'report_reason' => '卖家逾期未处理，默认同意'
            );
            foreach ($returns_shipping as $key => $returns)
            {
                $returns_ids[] = $returns['returns_id'];

                $log_data[] = array(
                    'returns_id' => $returns['returns_id'],
                    'operator' => '系统',
                    'remark' => '卖家超时未响应。本次申请自动确认。',
                    'log_time' => $now,
                );
            }

            /* 修改退货退款状态 */
            $returns_mod->edit('returns_id ' . db_create_in($returns_ids), $edit_data);

            /* 添加到退货退款日志表 */
            $returns_log_mod->add($log_data);
        }

        $this->log('auto_returns'); //记录日志
    }

    /**
     *    自动取消订单
     *    @author    libaoling
     *    @time      2014-09-03
     */
    function auto_cancel_order()
    {
        $now = gmtime();
        $interval = 3 * 24 * 3600; //默认3天

        $model_order = & m('order');

        $orders = $model_order->find(array(
            'fields' => 'order_id',
            'conditions' => "add_time + {$interval} < {$now} AND status = " . ORDER_PENDING,
        ));

        if (empty($orders))
        {
            $this->log('auto_cancel_order'); //记录日志
            return;
        }
        else
        {
            $model_order->edit(array_keys($orders), array('status' => ORDER_CANCELED, 'finished_time' => gmtime()));
            
            //写订单日志
            $order_logs = array();
            $order_log = & m('orderlog');
            foreach ($orders as $order_id => $order)
            {
                /* 加回商品库存 */
                $model_order->change_stock('+', $order_id);
                
                $order_logs[] = array(
                    'order_id' => $order_id,
                    'operator' => '0',
                    'order_status' => order_status(ORDER_PENDING),
                    'changed_status' => order_status(ORDER_CANCELED),
                    'remark' => '',
                    'log_time' => $now,
                );
            }
            $this->_unfreeze(array_keys($orders));
            $order_log->add($order_logs);
        }
        
        $this->log('auto_cancel_order'); //记录日志
    }

    /**
     *    自动把支付工具支付金额与余额支付金额分配到订单中
     *    @author    yanghj
     *    @time      2014-12-18
     */
    function auto_allot_order_money()
    {
        $now = gmtime();
        $temp= array();
        $add_data = array();

        $model_order = & m('order');
        $model_orderpay = & m('orderpay');
        $model_ordermoney = & m('ordermoney');
        $max_pay_time = $model_ordermoney->getOne("select max(pay_time) from {$model_ordermoney->table}");
        $max_pay_time = !empty($max_pay_time)?intval($max_pay_time):0;
        $orders= $model_order->find(array(
            'fields' => 'order_amount-order_amount as pay_money,order_amount as account_money,pay_time,order_id',
            'conditions' => "pay_time < {$now} AND pay_time > {$max_pay_time} AND payment_code = 'account' ",
            'order'  => 'pay_time asc, order_id asc',
        ));

        $sql = "SELECT op.out_trade_sn,o.pay_time,op.total_price,op.balance_price,op.order_price,op.order_id,op.pay_id FROM {$model_orderpay->table} op
        LEFT JOIN {$model_order->table} o on o.order_id = op.order_id
         WHERE o.pay_time < {$now} AND o.pay_time > {$max_pay_time} AND op.pay_time > 0 AND o.payment_code != 'account'
         GROUP BY  op.order_id
         ORDER BY o.pay_time asc, o.order_id asc";

        $order_pay = $model_orderpay->getAll($sql);

        if($order_pay)
        {
            foreach($order_pay as $key=>$val)
            {
                $temp[$val['out_trade_sn']]['total_price'] = $val['total_price'];
                $temp[$val['out_trade_sn']]['balance_price'] = $val['balance_price'];
                $temp[$val['out_trade_sn']]['orders'][$val['order_id']]['order_id'] = $val['order_id'];
                $temp[$val['out_trade_sn']]['orders'][$val['order_id']]['order_price'] = $val['order_price'];
                $temp[$val['out_trade_sn']]['orders'][$val['order_id']]['pay_time'] = $val['pay_time'];
            }
            foreach($temp as $k => $v)
            {
                $add_data = array_merge($add_data, $this->_allot_money($v));
            }
        }

        if($orders)
        {
            $add_data = array_merge($add_data, $orders);
        }

        if($add_data)
        {
            $rs = $model_ordermoney->add($add_data);
            if(!$rs){
                exit;
            };
        }
        $this->log('auto_allot_order_money'); //记录日志
        exit;
    }

    /**
     *    自动更新订单结算状态
     *    @author    yanghj
     *    @time      2015-01-09
     *   合适条件的订单  1.上个月支付的订单  2.买家确认订单时间在当月的3号之前 3.退货退款流程已经完成 4.只查询三个内的数据
     *
     */
    function auto_update_orders_clearing_status()
    {

        $order_clearing_mod = & m('orderclearing');
        $clearing_start_time = strtotime(date("Y-m").'-10');
        $max_valid_time = $clearing_start_time - 3600*24*7;
        $month_time  = strtotime(date("Y-m").'-01');
        $three_month_time = strtotime('-3 month');
        $sql = "SELECT c.id FROM ".DB_PREFIX."order_clearing c
        LEFT JOIN ".DB_PREFIX."order o ON c.order_id = o.order_id
        WHERE o.pay_time > 0  AND o.pay_time < {$month_time} AND o.finished_time > {$three_month_time} AND o.finished_time < {$max_valid_time} AND c.clearing_status = 0 AND c.order_id NOT IN
        (
        SELECT r.order_id FROM ".DB_PREFIX."returns r WHERE r.status IN (1,3,4,5,6,7) AND r.add_time > {$three_month_time} group by r.order_id
        ) ";

        $ids = $order_clearing_mod->getCol($sql);
        if($ids)
        {
            $order_clearing_mod->edit($ids, array('clearing_status'=>'1'));
            if ($order_clearing_mod->has_error())
            {
                exit;
            }
        }
        $this->log('auto_update_orders_clearing_status'); //记录日志
        exit;

    }


    /**
     *    自动把已经支付的订单插入订单结算表
     *    @author    yanghj
     *    @time      2015-01-15
     */
    function auto_insert_order_clearing()
    {
        $now = gmtime();
        $model_order = & m('order');
        $model_order_clearing = & m('orderclearing');
        $add_data = array();
        $interval_time =  60*60 ;//每次拉一个小时内的数据

        $get_time = $this->_get_start_time('auto_insert_order_clearing');
        if(empty($get_time))
        {
            $get_time = $model_order_clearing->getOne("select o.pay_time from {$model_order_clearing->table} as c left join {$model_order->table} as o on c.order_id = o.order_id where 1 order by id desc LIMIT 1");
        }

        $max_pay_time = !empty($get_time)?intval($get_time):0;
        if($max_pay_time == 0)
        {
            $end_pay_time = $now;
        }
        else
        {
            $end_pay_time = $max_pay_time + $interval_time > $now ? $now : $max_pay_time + $interval_time;
        }

        $orders= $model_order->find(array(
            'fields' => 'order_id,seller_id',
            'conditions' => "pay_time < {$end_pay_time} AND pay_time > {$max_pay_time} ",
            'order'  => 'pay_time asc, order_id asc',
        ));

        if($orders)
        {
            $i = 0;
            foreach($orders as $order)
            {
                $add_data[$i] = $order;
                $i++;
            }
            $rs = $model_order_clearing->add($add_data);
            if(!$rs){
                exit;
            };
        }
        $this->_get_start_time('auto_insert_order_clearing',$end_pay_time);
        $this->log('auto_insert_order_clearing'); //记录日志
        exit;
    }

    /**
     *    自动把注册会员的信息插入CRM客户资料管理表
     *    @author    yanghj
     *    @time      2015-01-30
     */
    function auto_insert_customer()
    {
        $now = gmtime();
        $model_member = & m('member');
        $model_customer = & m('customer');
        $add_data = array();
        $interval_time =  60*60 ;//每次拉一个小时内的数据

        $get_time = $this->_get_start_time('auto_insert_customer');
        if(empty($get_time))
        {
            $get_time = $model_customer->getOne("select max(reg_time) from {$model_customer->table} where source = 1");
        }

        $max_pay_time = !empty($get_time)?intval($get_time):0;
        if($max_pay_time == 0)
        {
            $end_pay_time = $now;
        }
        else
        {
            $end_pay_time = $max_pay_time + $interval_time > $now ? $now : $max_pay_time + $interval_time;
        }

        $sql = "SELECT u.user_name, u.im_qq, u.reg_time, s.binding_email, s.binding_mobile FROM ".DB_PREFIX."member u
        LEFT JOIN ".DB_PREFIX."user_safety s ON u.user_id = s.user_id
        WHERE u.reg_time < {$end_pay_time} AND u.reg_time > {$max_pay_time} AND  u.user_id NOT IN
        (
        SELECT user_id FROM ".DB_PREFIX."user_priv WHERE 1
        ) ORDER BY u.reg_time ASC";

        $members= $model_member->getAll($sql);

        if($members)
        {
            foreach($members as $key=>$val)
            {
                $add_data[$key]['user_name'] = $val['user_name'];
                $add_data[$key]['reg_time'] = $val['reg_time'];
                $add_data[$key]['im_qq'] = $val['im_qq'];
                $add_data[$key]['email'] = $val['binding_email'];
                $add_data[$key]['phone_mob'] = $val['binding_mobile'];
                $add_data[$key]['customer_ugrade'] = 4;
                $add_data[$key]['source'] = 1;
                $add_data[$key]['add_time'] = $val['reg_time'];
                $add_data[$key]['operator'] = '系统录入';
                $add_data[$key]['admin_name'] = 'admin';
            }
            $rs = $model_customer->add($add_data);
            if(!$rs){
                exit;
            };
        }
        $this->_get_start_time('auto_insert_customer',$end_pay_time);
        $this->log('auto_insert_customer'); //记录日志
        exit;
    }

    /**
     *    促销活动的开始与结束
     *    @author    yanghj
     *    @time      2015-04-16
     */
    function auto_execute_activity()
    {
        $now = gmtime();
        $activity_mod= & m('activity');
        $activity_goods_mod= & m('activitygoods');
        $cart_mod= & m('cart');
        $goods_mod= & m('goods');
        $start_activity = array();//已经开始的活动但还没有更新活动状态的数据
        $end_activity = array();//已经结束的活动但还没有更新活动状态的数据

        //查找还没有开始的活动和已经结束的活动
        $activity = $activity_mod->find(array(
            'fields' => 'act_id,start_time,end_time,discount_type,free_shipping,act_status',
            'conditions' => "(start_time < {$now} AND act_status = 0) OR (end_time < {$now} AND act_status = 1)",
        ));

        if($activity)
        {
            foreach($activity as $key=>$val)
            {
                if($val['act_status'] == 0)
                {
                    $start_activity[$key] = $val;
                }
                if($val['act_status'] == 1)
                {
                    $end_activity[$key] = $val;
                }

            }

            //处理已经开始的活动但还没有更新活动状态的数据
            if($start_activity)
            {
                $start_activity_ids = array_keys($start_activity);
                $sql = "SELECT c.rec_id,c.goods_id,c.price,c.retail_price,g.act_id,g.goods_id,g.promote_discount,g.promote_price FROM {$cart_mod->table} AS c left join {$activity_goods_mod->table} AS g on c.goods_id = g.goods_id  WHERE g.act_id " . db_create_in($start_activity_ids);
                $start_goods = $cart_mod->getAll($sql);
                if($start_goods)
                {
                    foreach($start_goods as $key=>$val)
                    {
                        if($val['promote_discount']>0)
                        {
                            $cart_data['price'] = $val['retail_price']*$val['promote_discount'];//如果是打折优惠,则商品价格=原价格*折扣
                        }
                        if($val['promote_price']>0)
                        {
                            $cart_data['price'] = $val['promote_price'];//如果是一口价优惠,则商品价格=一口价
                        }
                        if($start_activity[$val['act_id']]['free_shipping'] == 1)
                        {
                            $cart_data['shipping_id'] = 0;//如果是包邮优惠,则运费ID为0
                        }
                        $cart_mod->edit($val['rec_id'], $cart_data);//更新购物车的数据
                        if ($cart_mod->has_error())
                        {
                            exit;
                        }
                    }
                }
                $activity_mod->edit($start_activity_ids, array('act_status'=>1));//更新活动的状态
                if ($activity_mod->has_error())
                {
                    exit;
                }
            }

            //处理已经结束的活动但还没有更新活动状态的数据
            if($end_activity)
            {
                $end_activity_ids = array_keys($end_activity);
                $sql = "SELECT c.rec_id,c.goods_id,c.price,c.retail_price,g.act_id,g.goods_id,g.promote_discount,g.promote_price,go.shipping_id FROM {$cart_mod->table} AS c left join {$activity_goods_mod->table} AS g on c.goods_id = g.goods_id left join {$goods_mod->table} AS go on c.goods_id = go.goods_id  WHERE g.act_id " . db_create_in($end_activity_ids);
                $end_goods = $cart_mod->getAll($sql);
                if($end_goods)
                {
                    foreach($end_goods as $key=>$val)
                    {
                        $cart_data['price'] = $val['retail_price'];//还原商品价格
                        if($end_activity[$val['act_id']]['free_shipping'] == 1)
                        {
                            $cart_data['shipping_id'] = $val['shipping_id'];//如果是包邮优惠,则还原商品运费ID的值
                        }
                        $cart_mod->edit($val['rec_id'], $cart_data);//更新购物车的数据
                        if ($cart_mod->has_error())
                        {
                            exit;
                        }
                    }
                }
                $activity_mod->edit($end_activity_ids, array('act_status'=>2));//更新活动的状态
                if ($activity_mod->has_error())
                {
                    exit;
                }
            }
        }

        $this->log('auto_execute_activity'); //记录日志
        exit;
    }


    /**
     * 记录运行日志
     *
     * @param $file_name
     */
    function log($file_name = '')
    {
        if (empty($file_name))
            return;
        $content = "\r";
        $content .= date('Y-m-d H:i:s') . "\r\n";
        $path_root = ROOT_PATH . '/log/tasks_log/'.date('Y-m'); //绝对路径
        ecm_mkdir($path_root);
        $file = $path_root . '/' . $file_name . '.log';
        file_put_contents($file, $content, FILE_APPEND);
    }
    
    function _unfreeze($order_ids)
    {
        $orderpay_mod = m("orderpay");
        $out_trade_sns = array();
        $orderpays = $orderpay_mod->find(array(
            'conditions' => "order_id " . db_create_in($order_ids) . " AND flag = 0 AND pay_time = 0 group by order_id",
            'fields' => 'sum(balance_price) balance_price,out_trade_sn, user_id',
        ));
        
        foreach ($orderpays as $key => $orderpay)
        {
            $out_trade_sns[] = $orderpay['out_trade_sn'];
        }
        
        $bool = $orderpay_mod->edit("out_trade_sn " . db_create_in($out_trade_sns), array('flag' => 1));
        if($bool)
        {
            $sql = "";
            foreach ($orderpays as $key => $orderpay)
            {
                $sql .= "update wl_user_money set user_money = (user_money + {$orderpay['balance_price']}), frozen_money = (frozen_money - {$orderpay['balance_price']}) where user_id = '{$orderpay['user_id']}';";
            }
            $usermoney_mod = m("usermoney");
            $usermoney_mod->db->query($sql);
        }
        
    }

    /**
     * 根据外部交易号来分配金额到对应的订单里面
     *
     * @author    yanghj
     * @param $data array 数据来源
     */
    function _allot_money($data)
    {
        $arr = array();
        $sum_money = 0;
        $count = count($data['orders']);
        if($data['balance_price'] > 0)
        {
            if($data['balance_price'] == $data['total_price'])
            {
                //全部余额付款
                foreach($data['orders'] as $key => $val)
                {
                    $arr[$key]['pay_money'] = 0;
                    $arr[$key]['account_money'] = $val['order_price'];
                    $arr[$key]['pay_time'] = $val['pay_time'];
                    $arr[$key]['order_id'] = $val['order_id'];
                }
            }
            else
            {
                //余额付款与支付工具付款混合
                foreach($data['orders'] as $key => $val)
                {
                    $sum_money += $val['order_price'];
                    if($data['balance_price'] >= $sum_money)
                    {
                        $arr[$key]['pay_money'] = 0;
                        $arr[$key]['account_money'] = $val['order_price'];

                    }
                    else if ($data['balance_price'] < $sum_money &&  $data['balance_price'] > $sum_money - $data['orders'][$key]['order_price'] )
                    {
                        $arr[$key]['pay_money'] = $sum_money - $data['balance_price'];
                        $arr[$key]['account_money'] = $val['order_price'] - $arr[$key]['pay_money'];
                    }
                    else
                    {
                        $arr[$key]['pay_money'] = $val['order_price'];
                        $arr[$key]['account_money'] = 0;
                    }

                    $arr[$key]['pay_time'] = $val['pay_time'];
                    $arr[$key]['order_id'] = $val['order_id'];
                }
            }
        }
        else
        {
            //全部支付工具付款
            foreach($data['orders'] as $key => $val)
            {
                $arr[$key]['pay_money'] = $val['order_price'];
                $arr[$key]['account_money'] = 0;
                $arr[$key]['pay_time'] = $val['pay_time'];
                $arr[$key]['order_id'] = $val['order_id'];
            }
        }

        sort($arr);
        return $arr;
    }

    /**
     * 获取开始时间
     *
     */
    function _get_start_time($file_name,$time = 0)
    {
        if (empty($file_name))
            return;
        $start_time = 0;
        $path_root = ROOT_PATH . '/log/tasks_log/'.$file_name; //绝对路径
        ecm_mkdir($path_root);
        $file = $path_root . '/start_time.log';

        if(file_exists($file) && $time == 0)
        {
            $start_time = file_get_contents($file);
        }
        else
        {
            $start_time = $time;
            file_put_contents($file, $start_time);
            @chmod($file, 0755);
        }
        return intval($start_time);

    }

    /**
     * 生成自动好评的时间(买家确认收货日期+7天+8:00~24:00之间随机时间)
     *
     * @author    yanghj
     * @param $finished_time 买家确认收货时间
     *
     */
    function _get_auto_evaluate_time($finished_time = 0)
    {
        $evaluate_time = 0;
        if (intval($finished_time) <= 0)
        {
            return $evaluate_time;
        }
        $evaluate_time = strtotime(date('Y-m-d',$finished_time+25200)) + rand(28800,86400);
        return $evaluate_time;
    }

    /**
     * 生成自动好评的内容
     *
     */
    function _get_auto_evaluate_comment()
    {
        $arr = array(
            1=>'商品质量很好，客服服务周到，快递迅速送达，好评！',
            2=>'价格和质量都很满意！支持！',
            3=>'东西不错，质量非常好，满意 ！',
            4=>'才收到货，迫不及待来评论，非常满意万菱的产品！',
            5=>'商品描述相符，实物感觉相当不错。',
            6=>'和实体店的一样，不过网站购入方便很多，支持。',
            7=>'看上去不错，快递也挺好，非常满意~',
            8=>'送货比较准时，看上去挺好的~质量过关。',
            9=>'这次是我最满意的一次网购，东西真心不错，在这里还要表扬一下客服，服务非常到位。',
            10=>'东西很不错，以后还来买 ，可以省下逛场子的时间了。',
        );
        $key = rand(1,10);
        return $arr[$key];
    }

}

?>
